<template>
  <div class="answer-management">
    <el-card shadow="hover" class="answers-card">
      <!-- 搜索和过滤组件 -->
      <div class="filter-bar">
        <el-input
          v-model="answerKeyword"
          placeholder="搜索回答内容"
          class="search-input"
          clearable
          @keyup.enter="getAnswers"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-button type="primary" @click="getAnswers" style="margin-left: 10px;">
          <el-icon><Search /></el-icon>查询
        </el-button>
      </div>
      
      <!-- 回答列表 -->
      <el-table
        v-loading="loading"
        :data="answers"
        style="width: 100%; margin-top: 20px;"
        border
        @selection-change="handleAnswerSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content" label="内容" min-width="280" show-overflow-tooltip />
        <el-table-column prop="questionTitle" label="问题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="userName" label="回答者" width="120" />
        <el-table-column prop="voteCount" label="点赞" width="80" sortable />
        <el-table-column prop="commentCount" label="评论" width="80" sortable />
        <el-table-column prop="isAccepted" label="是否采纳" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isAccepted ? 'success' : 'info'">
              {{ scope.row.isAccepted ? '已采纳' : '未采纳' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="回答时间" width="180" />
        <el-table-column label="操作" fixed="right" width="170">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              plain
              @click="navigateToQuestion(scope.row.questionId, scope.row.id)"
            >查看</el-button>
            <el-button
              type="danger"
              size="small"
              plain
              @click="deleteAnswer(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 批量操作 -->
      <AnswerBatchActions
        v-if="selectedAnswers.length > 0"
        :count="selectedAnswers.length"
        @batch-delete="batchDeleteAnswers"
      />
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { 
  getAnswers as apiGetAnswers,
  deleteAnswer as apiDeleteAnswer,
  batchDeleteAnswers as apiBatchDeleteAnswers
} from '../../api/admin';
import AnswerBatchActions from './AnswerBatchActions.vue';

const props = defineProps({});
const emit = defineEmits(['refresh']);
const router = useRouter();

// 回答管理相关
const answers = ref([]);
const answerKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedAnswers = ref([]);
const loading = ref(false);

// 获取回答列表
const getAnswers = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      keyword: answerKeyword.value
    };
    
    const response = await apiGetAnswers(params);
    if (response.code === 200) {
      answers.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取回答列表失败');
    }
  } catch (error) {
    console.error('获取回答列表失败:', error);
    ElMessage.error('获取回答列表失败: ' + (error.message || '未知错误'));
    answers.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 处理回答选择变化
const handleAnswerSelectionChange = (selection) => {
  selectedAnswers.value = selection;
};

// 处理回答分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getAnswers();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getAnswers();
};

// 删除回答
const deleteAnswer = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除此回答吗？此操作不可恢复!', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    });
    
    loading.value = true;
    const response = await apiDeleteAnswer(id);
    if (response.code === 200) {
      ElMessage.success('回答已删除');
      getAnswers();
    } else {
      ElMessage.error(response.message || '删除回答失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除回答失败:', error);
      ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    }
  } finally {
    loading.value = false;
  }
};

// 批量删除回答
const batchDeleteAnswers = async () => {
  if (selectedAnswers.value.length === 0) {
    ElMessage.warning('请选择要删除的回答');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedAnswers.value.length}个回答吗？此操作不可恢复！`, '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    });
    
    const answerIds = selectedAnswers.value.map(answer => answer.id);
    const response = await apiBatchDeleteAnswers(answerIds);
    
    if (response.code === 200) {
      ElMessage.success(`已删除${response.data || selectedAnswers.value.length}个回答`);
      getAnswers();
    } else {
      ElMessage.error(response.message || '批量删除回答失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除回答失败:', error);
      ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    }
  }
};

// 导航到问题详情页并定位到回答
const navigateToQuestion = (questionId, answerId) => {
  if (!questionId) {
    ElMessage.warning('问题ID不存在，无法跳转');
    return;
  }
  
  try {
    // 使用路由跳转
    router.push({
      path: `/question/${questionId}`,
      query: answerId ? { answerId } : {}
    });
  } catch (error) {
    console.error('页面跳转失败:', error);
    ElMessage.error('页面跳转失败');
  }
};

// 初始化
onMounted(() => {
  getAnswers();
});

// 暴露方法给父组件
defineExpose({
  getAnswers
});
</script>

<style scoped>
.answer-management {
  width: 100%;
}

.answers-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-input {
    width: 100%;
  }
  
  .filter-bar .el-button {
    width: 100%;
    margin-left: 0 !important;
  }
}
</style> 